<template>
    <h2 style="text-align: center;">商品修改</h2>
    <el-form
      ref="ruleFormRef"
      style="max-width: 600px"
      :model="Info"
      :rules="rules"
      label-width="auto"
      class="demo-ruleForm"
      :size="formSize"
      status-icon
    >
    <!-- 输入框 -->
      <el-form-item label="商品名称" prop="Goods_Name">
        <el-input v-model="Info.Goods_Name" />
      </el-form-item>

      <!-- 下拉框 -->
      <el-form-item label="商品品牌" prop="Brand_Id">
          <el-select v-model="Info.Brand_Id" placeholder="请选择商品品牌">
            <el-option v-for="item in InfoBrand" :label="item.Brand_Name" :value="item.Brand_Id" />
          </el-select>
      </el-form-item>

      <!-- 分类级联选择器 -->
      <el-form-item label="商品分类" prop="count">
        <div class="m-4">
          <el-cascader v-model="Info.GT_Id" :options="InfoType" :props="props" @change="handleChange"/>
        </div>
      </el-form-item>

      <!-- 输入框 -->
      <el-form-item label="商品价格" prop="Goods_Price">
        <el-input v-model="Info.Goods_Price" />
      </el-form-item>

      <!-- 图片 -->
      <el-form-item label="图片" prop="Goods_Img">
        <el-upload
            class="avatar-uploader"
            action="https://localhost:44377/api/FilesUpLoads/UpLoads"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="Info.Goods_Img" :src="Info.Goods_Img" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
      </el-form-item>

      <!-- 单选框 -->
      <el-form-item label="状态" prop="Goods_State">
        <el-radio-group v-model="Info.Goods_State">
          <el-radio :value="true">上架</el-radio>
          <el-radio :value="false">下架</el-radio>
        </el-radio-group>
      </el-form-item>

      <!-- 富文本编辑器 -->
      <el-form-item label="商品描述" prop="Goods_Desc">
        <div style="border: 1px solid #ccc">
            <Toolbar
              style="border-bottom: 1px solid #ccc"
              :editor="editorRef"
              :defaultConfig="toolbarConfig"
              :mode="mode"
            />
            <Editor
              style="height: 500px; overflow-y: hidden;"
              v-model="Info.Goods_Desc"
              :defaultConfig="editorConfig"
              :mode="mode"
              @onCreated="handleCreated"
            />
          </div>
      </el-form-item>

      <!-- 按钮 -->
      <el-form-item>
        <el-button type="primary" @click="submitForm(ruleFormRef)">
          修改商品信息
        </el-button>
        <el-button @click="resetForm(ruleFormRef)" style="margin-right: 10px;">重置</el-button>
        <a href="/ShowGoods">返回列表</a>
      </el-form-item>
      
    </el-form>
  </template>
  
<script lang="ts" setup>
    import { reactive, ref,onMounted } from 'vue'
    import type { ComponentSize, FormInstance, FormRules } from 'element-plus'
    import axios from 'axios'
    import '@wangeditor/editor/dist/css/style.css' // 引入 css
    import { ElMessage } from 'element-plus'//导入提示信息
    import type { UploadProps } from 'element-plus'//图片使用
    import { Plus } from '@element-plus/icons-vue'
    import { onBeforeUnmount, shallowRef } from 'vue'
    import { Editor, Toolbar } from '../../../node_modules/@wangeditor/editor-for-vue' //需要../../
    import { useRouter,useRoute } from 'vue-router'

    const router=useRouter();
    const route=useRoute();
  
    const formSize = ref<ComponentSize>('default')
    const ruleFormRef = ref<FormInstance>()
    //修改响应式数据
    const Info:any = ref({
        Goods_SnowID:route.params.id,
        Goods_Name: "",
        Brand_Id: "",
        GT_Id: "",
        Goods_Price: "",
        Goods_Img: "",
        Goods_Desc: "",
        Goods_State: true,
    })
    //品牌响应式数据
    const InfoBrand=ref([{
        Brand_Id: 0,
        Brand_Name: "",
    }])
    //钩子函数
    onMounted(()=>{
        GetBrands();//获取品牌信息
        ShowGoodsType();//获取类型级联选择器
        FanTian();//反填
    })
    //反填
    const FanTian=()=>{
      axios.get("https://localhost:44377/api/Goods/GetGoodsInfo?id="+route.params.id)
      .then(res=>{
        Info.value=res.data.Data;
        Info.value.GT_Id=Info.value.GT_Id.split(",").map(Number);
      })
    }
    //获取品牌信息
    const GetBrands=()=>{
        axios.get("https://localhost:44377/api/Goods/GetGoodsBrand")
        .then(res=>{
            InfoBrand.value=res.data.Data
        })
    }
    const locationOptions = ['Home', 'Company', 'School']
    //验证
    const rules = reactive<FormRules>({
      Goods_Name: [
            { required: true, message: '商品名称不能为空！', trigger: 'blur' },
            { min: 3, max: 5, message: '商品名称需介于3-5个字符', trigger: 'blur' },
        ],
      Goods_Price: [
            { required: true, message: '商品价格不能为空！', trigger: 'blur' },
        ],
      Brand_Id: [
            {
                required: true,
                message: '请选择商品品牌',
                trigger: 'change',
            },
        ],
    })
    //按钮
    const submitForm = async (formEl: FormInstance | undefined) => {
        Info.value.GT_Id=Info.value.GT_Id.toString();
        if (!formEl) return
        await formEl.validate((valid, fields) => {
        if (valid) {
            console.log('数据效验成功，可以执行添加操作!')
            axios.put("https://localhost:44377/api/Goods/UpdGoodsInfo",Info.value)
            .then(res=>{
                if(res.data.Data==-1)
                {
                    ElMessage.success('商品名称已存在，，请重新输入！');
                }
                else if(res.data.Data>0)
                {
                     ElMessage.success('商品信息修改成功');
                     router.push("/ShowGoods");//跳转到显示页面
                }
                else
                {
                    ElMessage.success('商品信息修改失败');
                }
            })
        } else {
            console.log('数据参数有问题，请检查!', fields)
        }
        })
    }
    //重置
    const resetForm = (formEl: FormInstance | undefined) => {
        if (!formEl) return
        formEl.resetFields()
    }
// ---------------------------------------------级联选择器----------------------------------------//
    //级联选择器响应式数据
    const InfoType=ref([])
    const props = {
        expandTrigger: 'hover' as const,
    }
    //加载级联选择器方法
    const ShowGoodsType=()=>{
        axios.get("https://localhost:44377/api/Goods/ShowGoodsType?Pid=0")
        .then(res=>{
            InfoType.value=res.data.Data
        })
    }
    //获取选中的商品类型id
    const handleChange = (value:any) => {
        Info.value.GT_Id=value.toString();
    }


    //------------------------------------------文件上传--------------------------------------------//
  
    //上传方法
    const handleAvatarSuccess=(img:any)=>{
      Info.value.Goods_Img=img;
    }
    //图片验证格式
    const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
        if (rawFile.type !== 'image/jpeg') {
        ElMessage.error('图片类型必须为JPG格式!')
        return false
        } else if (rawFile.size / 1024 / 1024 > 2) {
        ElMessage.error('图片大小不能超过2MB!')
        return false
        }
        return true
    }
  
    // -----------------------------------------富文本编辑器----------------------------------------//
    // 编辑器实例，必须用 shallowRef
    const editorRef = shallowRef()

    //文本响应式数据
    const mode=ref();

    // 内容 HTML
    const valueHtml = ref('<p>hello</p>')
    
    const toolbarConfig = {}
    const editorConfig = { placeholder: '请输入内容...' }

    // 组件销毁时，也及时销毁编辑器
    onBeforeUnmount(() => {
      const editor = editorRef.value
      if (editor == null) return
      editor.destroy()
    })

    const handleCreated = (editor:any) => {
      editorRef.value = editor // 记录 editor 实例，重要！
    }
    const options = Array.from({ length: 10000 }).map((_, idx) => ({
        value: `${idx + 1}`,
        label: `${idx + 1}`,
    }))
</script>


<style scoped>
    .avatar-uploader .avatar {
        width: 178px;
        height: 178px;
        display: block;
    }
</style>
    
<style>
    .avatar-uploader .el-upload {
        border: 1px dashed var(--el-border-color);
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
        transition: var(--el-transition-duration-fast);
    }
    
    .avatar-uploader .el-upload:hover {
        border-color: var(--el-color-primary);
    }
    
    .el-icon.avatar-uploader-icon {
        font-size: 28px;
        color: #8c939d;
        width: 178px;
        height: 178px;
        text-align: center;
    }
</style>
  